package com.uchedao.vehicledetection.activity;

import android.content.Context;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.uchedao.vehicledetection.R;
import com.uchedao.vehicledetection.utils.CameraUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;

public class CameraActivity extends CJDBaseActivity {

    private TextView tvTitle;
    private Button btnReplay;
    private Button btnTake;
    private Button btnNext;
    private SurfaceView surfaceView;

    private Camera camera;

    private int camera_id = 0;
    private int camera_direction = Camera.CameraInfo.CAMERA_FACING_BACK;
    private IOrientationEventListener iOriListener;

    final int SUCCESS = 233;
    SnapHandler handler = new SnapHandler();

    @Override
    protected void onSetting() {
        super.onSetting();
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    protected String getActivityTag() {
        return "CameraActivity";
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_camera;
    }

    public void initView() {
        btnReplay = (Button) findViewById(R.id.btnCameraReplay);
        btnTake = (Button) findViewById(R.id.btnCameraTake);
        btnNext = (Button) findViewById(R.id.btnCameraNext);
        surfaceView = (SurfaceView) findViewById(R.id.surfaceCamera);
    }

    @Override
    protected void initData() {

    }

    public void initListener() {
        btnTake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                camera.takePicture(null, null, new Camera.PictureCallback(){

                    @Override
                    public void onPictureTaken(byte[] data, Camera camera) {
                        // TODO Auto-generated method stub
                        final byte[] tempdata = data;
                        Thread thread = new Thread(new Runnable(){

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                File dir = new File("mnt/sdcard/testcamera");
                                if(!dir.exists())
                                {
                                    dir.mkdirs();
                                }
                                String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance()) + ".jpg";
                                File f = new File("mnt/sdcard/testcamera/" +name);
                                if(!f.exists())
                                {
                                    try {
                                        f.createNewFile();
                                    } catch (IOException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }
                                FileOutputStream outputStream;
                                try {
                                    outputStream = new FileOutputStream(f);
                                    outputStream.write(tempdata);
                                    outputStream.close();
                                } catch (FileNotFoundException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                Log.v("TestCameraActivityTag", "store success");
                                handler.sendEmptyMessage(SUCCESS);
                            }

                        });
                        thread.start();
                    }

                });
            }
        });

        surfaceView.getHolder().setKeepScreenOn(true);
        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback(){

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                // TODO Auto-generated method stub
                int mNumberOfCameras = Camera.getNumberOfCameras();

                // Find the ID of the default camera
                Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
                for (int i = 0; i < mNumberOfCameras; i++)
                {
                    Camera.getCameraInfo(i, cameraInfo);
                    if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK)
                    {
                        camera_id = i;
                    }
                }
                camera = Camera.open(camera_id);
                try {
                    camera.setPreviewDisplay(holder);
                    camera.startPreview();

                    iOriListener.enable();

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format,
                                       int width, int height) {
                // TODO Auto-generated method stub
                setCameraAndDisplay(width, height);

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                // TODO Auto-generated method stub
                if(null != camera)
                {
                    camera.release();
                    camera = null;
                }

            }

        });

        iOriListener = new IOrientationEventListener(this);
    }

    private void switchCamera() {
        if(camera_direction == Camera.CameraInfo.CAMERA_FACING_BACK)
            camera_direction = Camera.CameraInfo.CAMERA_FACING_FRONT;
        else
            camera_direction = Camera.CameraInfo.CAMERA_FACING_BACK;

        int mNumberOfCameras = Camera.getNumberOfCameras();
        Camera.CameraInfo info = new Camera.CameraInfo();
        for(int i=0; i<mNumberOfCameras; i++) {
            Camera.getCameraInfo(i, info);
            if(info.facing == camera_direction)
                camera_id = 1;
        }

        if(camera != null) {
            camera.stopPreview();
            camera.release();
        }

        camera = Camera.open(camera_id);
        try {
            camera.setPreviewDisplay(surfaceView.getHolder());
            camera.startPreview();
        } catch(Exception e) {
            e.printStackTrace();
        }
        setCameraAndDisplay(surfaceView.getWidth(), surfaceView.getHeight());
    }

    public void setCameraAndDisplay(int width, int height) {
        Camera.Parameters parameters = camera.getParameters();
        // 获取摄像头支持的PictureSize列表
        List<Camera.Size> picSizeList = parameters.getSupportedPictureSizes();
        // 从列表中选取合适的分辨率
        Camera.Size picSize = CameraUtils.getProperSize(picSizeList, ((float) width/height));
        if(picSize != null)
            parameters.setPictureSize(picSize.width, picSize.height);
        else
            picSize = parameters.getPictureSize();

        //获取摄像头支持的PreviewSize列表
        List<Camera.Size> previewSizeList = parameters.getSupportedPreviewSizes();
        Camera.Size preSize = CameraUtils.getProperSize(previewSizeList, ((float)width)/height);
        if(null != preSize)
        {
            Log.v("TestCameraActivityTag", preSize.width + "," + preSize.height);
            parameters.setPreviewSize(preSize.width, preSize.height);
        }

        /*根据选出的PictureSize重新设置SurfaceView大小*/
        float w = picSize.width;
        float h = picSize.height;
        surfaceView.setLayoutParams(new RelativeLayout.LayoutParams( (int)(height*(w/h)), height));

        parameters.setJpegQuality(100); // 设置照片质量

        //连续聚焦
        if (parameters.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE))
        {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        }
        camera.cancelAutoFocus();//自动对焦
        camera.setDisplayOrientation(0);
        camera.setParameters(parameters);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        this.iOriListener.disable();
    }

    public class IOrientationEventListener extends OrientationEventListener {
        public IOrientationEventListener(Context context) {
            super(context);
        }

        @Override
        public void onOrientationChanged(int orientation) {
            if(ORIENTATION_UNKNOWN == orientation)
                return;

            Camera.CameraInfo info =  new Camera.CameraInfo();
            Camera.getCameraInfo(camera_id, info);
            orientation = (orientation+45) / 90 * 90;
            int rotation = 0;
            if(info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT)
                rotation = (info.orientation + orientation + 360) % 360;
            else
                rotation = (info.orientation + orientation) % 360;

            if(camera != null) {
                Camera.Parameters parameters = camera.getParameters();
                parameters.setRotation(rotation);
                camera.setParameters(parameters);
            }
        }
    }

    class SnapHandler extends Handler
    {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            if(msg.what == SUCCESS)
            {

            }
            try {
                camera.setPreviewDisplay(surfaceView.getHolder());
                camera.startPreview();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}
